package com.xhtt.modules.msg.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.msg.dao.MsgInfoMapper;
import com.xhtt.modules.msg.entity.MsgInfo;
import com.xhtt.modules.msg.entity.MsgUser;
import com.xhtt.modules.msg.model.AppVersion;
import com.xhtt.modules.msg.service.MsgInfoService;
import com.xhtt.modules.msg.service.MsgUserService;
import com.xhtt.modules.task.entity.TaskCarPlan;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 消息表 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-03-26
 */
@Service
public class MsgInfoServiceImpl extends ServiceImpl<MsgInfoMapper, MsgInfo> implements MsgInfoService {

    @Autowired
    private MsgUserService msgUserService;

    @Override
    public PageUtils msgList(Map<String, Object> params) {
        Page<MsgInfo> page = new Query<MsgInfo>(params).getPage();
        page.setRecords(baseMapper.msgList(page, params));
        return new PageUtils(page);
    }

    @Override
    public Map<String, MsgInfo> mapMaxDate(Integer userId) {
        Map<String, MsgInfo> map = new HashMap<>();
        List<MsgInfo> list = baseMapper.mapMaxDate(userId);
        for (MsgInfo msg : list) {
            map.put(msg.getMainType(), msg);
        }
        return map;
    }

    @Override
    @Transactional
    public void saveMsgBatch(List<MsgInfo> msgInfoList) {
        if (CollectionUtils.isNotEmpty(msgInfoList)) {
            this.saveBatch(msgInfoList);

            List<MsgUser> msgUsers = new ArrayList<>();
            MsgUser msgUser;

            Set<Integer> userIds;
            for (MsgInfo msgInfo : msgInfoList) {
                userIds = msgInfo.getUserIdList();
                if (CollectionUtils.isNotEmpty(userIds)) {
                    for (Integer uid : userIds) {
                        msgUser = new MsgUser(msgInfo.getId(), uid);
                        msgUsers.add(msgUser);
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(msgUsers)) {
                msgUserService.saveBatch(msgUsers);
            }
        }
    }

    @Override
    public AppVersion appVersion() {
        return baseMapper.appVersion();
    }
}
